#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2020-12-22 9:09 上午
# @Author  : yangdy
# @File    : 2020-12-22.103.二叉树的锯齿形层序遍历
# @Software: PyCharmCE
from tools.my_methods import *


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        ans, que = [[root.val]], [root]
        p = 0
        while que:
            qq = []
            for qi in que:
                if qi.left:
                    qq.append(qi.left)
                if qi.right:
                    qq.append(qi.right)
            if p:
                data = [qq[i].val for i in filter(lambda x: qq[x], range(len(qq)))]
            else:
                data = [qq[i].val for i in filter(lambda x: qq[x], range(len(qq) -1, -1, -1))]
            if data:
                ans.append(data)
            else:
                break
            que = qq
            p = 1 - p
        return ans
